import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    // 共享的数据
    // 所有的任务列表
    list: [],
    inputValue: '',
    nextId: 6,
    viewkey: 'all'
  },
  // 包装数据但不改变数据
  getters: {
    undonelength(state) {
      return state.list.filter(x => x.done === false).length
    },
    infolist(state) {
      if (state.viewkey === 'all') return state.list
      if (state.viewkey === 'undone') return state.list.filter(x => x.done === false)
      if (state.viewkey === 'done') return state.list.filter(x => x.done === true)
    }
  },
  mutations: {
    // 改变数据
    // 初始化任务列表
    initList(state, list) {
      state.list = list
    },
    // 为文本框内容赋值
    setinputvalue(state, val) {
      state.inputValue = val
    },
    // 添加任务项
    additem(state) {
      const item = {
        id: state.nextId,
        info: state.inputValue.trim(),
        done: false
      }
      state.list.push(item)
      state.nextId++
      state.inputValue = ''
    },
    // 删除任务项
    removeitem(state, id) {
      // state.list = state.list.filter(x => x.id !== id)

      const i = state.list.findIndex(x => x.id === id)
      if (i !== -1) {
        state.list.splice(i, 1)
      }
    },
    // 复选框状态变化
    statechange(state, obj) {
      // state.list.find(x => x.id === obj.id).done = obj.state

      const i = state.list.findIndex(x => x.id === obj.id)
      if (i !== -1) {
        state.list[i].done = obj.state
      }
    },
    cleardone(state) {
      state.list = state.list.filter(x => x.done === false)
    },
    changeview(state, key) {
      state.viewkey = key
    }
  },
  actions: {
    // 异步操作
    getList(context) {
      // 文件路径是个坑
      axios.get('/data.json').then(({ data }) => {
        console.log(data)
        context.commit('initList', data)
      })
    }
  },
  modules: {
  }
})
